<template>
  <div class="cleanup-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <el-icon><Delete /></el-icon>
          <span style="margin-left: 8px;">备份清理</span>
        </div>
      </template>

      <el-alert
        title="自动清理策略"
        type="info"
        :closable="false"
        style="margin-bottom: 20px;"
      >
        <p>系统会自动保留每个设备最新的 <strong>{{ maxBackups }}个备份</strong>，超出数量的旧备份会被自动清理。</p>
        <p>清理策略：每次备份成功后自动执行，确保磁盘空间不会无限增长。</p>
      </el-alert>

      <el-card style="margin-bottom: 20px;">
        <template #header>
          <div class="card-header">
            <el-icon><Setting /></el-icon>
            <span style="margin-left: 8px;">清理配置</span>
          </div>
        </template>

        <el-form :model="configForm" label-width="200px">
          <el-form-item label="每个设备最大保留备份数">
            <el-row :gutter="10" style="width: 100%;">
              <el-col :span="12">
                <el-slider
                  v-model="configForm.maxBackups"
                  :min="1"
                  :max="20"
                  :marks="backupMarks"
                  :show-tooltip="false"
                />
              </el-col>
              <el-col :span="12">
                <el-input-number
                  v-model="configForm.maxBackups"
                  :min="1"
                  :max="50"
                  controls-position="right"
                  style="width: 150px;"
                />
                <span style="margin-left: 10px; color: #666;">个备份</span>
              </el-col>
            </el-row>
            <div style="margin-top: 10px; color: #999; font-size: 12px;">
              <el-icon><InfoFilled /></el-icon>
              建议设置：测试环境 1-3 个，生产环境 3-10 个
            </div>
          </el-form-item>

          <el-form-item>
            <el-button 
              type="primary" 
              @click="saveConfig" 
              :loading="saving"
              size="large"
            >
              <el-icon><Check /></el-icon>
              保存配置
            </el-button>
            <el-button @click="loadConfig" size="large">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="action-card">
            <template #header>
              <div class="card-header">
                <el-icon><Operation /></el-icon>
                <span>手动清理</span>
              </div>
            </template>

            <el-button 
              type="primary" 
              @click="cleanupAll" 
              :loading="cleaning"
              size="large"
              style="width: 100%; margin-bottom: 15px;"
            >
              <el-icon><Delete /></el-icon>
              清理所有设备的旧备份
            </el-button>

            <div style="color: #666; font-size: 12px; text-align: center;">
              将清理所有设备超出限制的旧备份
            </div>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card class="action-card">
            <template #header>
              <div class="card-header">
                <el-icon><InfoFilled /></el-icon>
                <span>清理统计</span>
              </div>
            </template>

            <el-button 
              @click="loadStats" 
              :loading="loading"
              size="large"
              style="width: 100%; margin-bottom: 15px;"
            >
              <el-icon><Refresh /></el-icon>
              刷新统计信息
            </el-button>

            <div style="color: #666; font-size: 12px; text-align: center;">
              查看各设备的备份数量情况
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-divider />

      <div v-if="Object.keys(backupStats).length > 0">
        <h3>设备备份统计</h3>
        <el-table :data="statsTableData" stripe>
          <el-table-column prop="device_name" label="设备名称" width="200" />
          <el-table-column label="当前备份数" width="120">
            <template #default="{ row }">
              <el-tag :type="row.backup_count > 3 ? 'warning' : 'success'" size="small">
                {{ row.backup_count }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="最大保留数" width="120">
            <template #default="{ row }">
              <el-tag type="info" size="small">{{ row.max_allowed }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="row.needs_cleanup ? 'warning' : 'success'" size="small">
                {{ row.needs_cleanup ? '需要清理' : '正常' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button 
                v-if="row.needs_cleanup"
                type="warning" 
                size="small" 
                @click="cleanupDevice(row.device_id)"
                :loading="cleaning"
              >
                清理此设备
              </el-button>
              <span v-else style="color: #999;">无需清理</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-else-if="!loading" class="empty-state">
        <el-empty description="暂无设备数据" />
      </div>
    </el-card>

    <el-card style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <el-icon><QuestionFilled /></el-icon>
          <span style="margin-left: 8px;">清理说明</span>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <el-icon color="#1890ff" :size="24"><Clock /></el-icon>
            <div>
              <h4>自动清理</h4>
              <p>每次备份成功后自动执行，无需手动干预</p>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <el-icon color="#52c41a" :size="24"><Shield /></el-icon>
            <div>
              <h4>灵活配置</h4>
              <p>可自定义每个设备保留的备份数量</p>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <el-icon color="#faad14" :size="24"><Warning /></el-icon>
            <div>
              <h4>空间管理</h4>
              <p>防止磁盘空间被大量备份文件占满</p>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { cleanupApi } from '@/api'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const cleaning = ref(false)
const saving = ref(false)
const backupStats = ref({})
const maxBackups = ref(3)
const configForm = ref({
  maxBackups: 3
})

// 滑块标记点
const backupMarks = {
  1: '1个',
  3: '3个',
  5: '5个',
  10: '10个',
  15: '15个',
  20: '20个'
}

const statsTableData = computed(() => {
  return Object.values(backupStats.value).map(device => ({
    device_name: device.device_name || `设备${device.device_id}`,
    device_id: device.device_id,
    backup_count: device.backup_count,
    max_allowed: device.max_allowed,
    needs_cleanup: device.needs_cleanup
  }))
})

const loadStats = async () => {
  loading.value = true
  try {
    backupStats.value = await cleanupApi.getBackupStats()
  } catch (error) {
    ElMessage.error('加载统计信息失败')
  } finally {
    loading.value = false
  }
}

const loadConfig = async () => {
  try {
    const config = await cleanupApi.getCleanupConfig()
    maxBackups.value = config.max_backups_per_device
    configForm.value.maxBackups = config.max_backups_per_device
  } catch (error) {
    ElMessage.error('加载配置失败')
  }
}

const saveConfig = async () => {
  if (configForm.value.maxBackups === maxBackups.value) {
    ElMessage.info('配置未改变')
    return
  }

  saving.value = true
  try {
    const result = await cleanupApi.updateMaxBackups(configForm.value.maxBackups)
    if (result.success) {
      maxBackups.value = configForm.value.maxBackups
      ElMessage.success(result.message)
      loadStats() // 刷新统计信息
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.detail || '保存配置失败')
  } finally {
    saving.value = false
  }
}

const cleanupAll = async () => {
  cleaning.value = true
  try {
    const result = await cleanupApi.cleanupAll()
    if (result.success) {
      ElMessage.success(result.message)
      loadStats() // 刷新统计
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    ElMessage.error('清理失败')
  } finally {
    cleaning.value = false
  }
}

const cleanupDevice = async (deviceId) => {
  cleaning.value = true
  try {
    const result = await cleanupApi.cleanupDevice(deviceId)
    if (result.success) {
      ElMessage.success(result.message)
      loadStats() // 刷新统计
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    ElMessage.error('清理失败')
  } finally {
    cleaning.value = false
  }
}

onMounted(() => {
  loadConfig()
  loadStats()
})
</script>

<style scoped>
.action-card {
  height: 200px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 500;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  height: 100%;
}

.info-item h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
}

.info-item p {
  margin: 0;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}
</style>

